package is.model;

import is.interfaces.Bean;
import is.model.bean.Department;
import is.model.bean.Employee;
import is.model.exceptions.DeletingLinkedObjectException;
import java.sql.*;

/**
 *
 * @author aspr0
 */
public class Restriction
{
    public static void checkRegionDeletion(Bean region) throws SQLException, DeletingLinkedObjectException
    {
        checkDeletion(region, new Department(), 3);
        checkDeletion(region, region, 0);
    }

    public static void checkDepartmentDeletion(Bean department) throws SQLException, DeletingLinkedObjectException
    {
        checkDeletion(department, new Employee(), 3);
        checkDeletion(department, department, 1);
    }

    private static void checkDeletion(Bean target, Bean linked, Integer linkFieldIndex) throws SQLException,
                                                                                               DeletingLinkedObjectException
    {
        String query = "select count(*) count from %s where %s = ?";
        query = String.format(query, linked.getTableName(), linked.getFields()[linkFieldIndex]); // TODO insert without SINGLE QUOTES

        PreparedStatement ps = DataSource.getConnection().prepareStatement(query);
        ps.setInt(1, target.getId());

        ps.execute();

        ResultSet resultSet = ps.getResultSet();
        resultSet.next();

        if (resultSet.getInt("count") > 0)
        {
            throw new DeletingLinkedObjectException();
        }
    }
}
